<template>
  <div>
    <el-col :span="1" />
    <el-col :span="11">
      <el-row>
        <el-form-item
          label="任务名称"
          prop="scriptPackName"
        >
          <el-input
            v-model="form.scriptPackName"
            clearable
            size="large"
            style="width: 300px"
            placeholder="请输入任务名称"
            :disabled="disableForm"
          />
        </el-form-item>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-form-item
          label="选择集群"
          prop="clusterId"
        >
          <el-select
            v-model="form.clusterId"
            size="large"
            style="width: 300px"
            placeholder="请选择集群"
            :disabled="disableForm"
          >
            <el-option
              v-for="item in clusterList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-row>
    </el-col>
    <el-col :span="12">
      <el-row>
        <el-form-item
          style="margin-top: 8px"
          label="文件获取方式"
          prop="exportType"
        >
          <el-radio-group
            v-model="form.fileObtainingType"
            :disabled="disableForm"
          >
            <el-radio label="git">git链接</el-radio>
            <el-radio label="upload">上传文件</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <el-row
        v-if="form.fileObtainingType === 'git'"
        style="margin-top: 20px"
      >
        <el-form-item
          label="Git链接"
          prop="gitUrl"
        >
          <!-- <el-input
            v-model="form.gitUrl"
            size="large"
            style="width: 300px"
            type="text"
          /> -->
          <el-select
            v-model="form.gitUrl"
            size="large"
            filterable
            clearable
            placeholder="请选择git标识"
            style="width: 300px"
            :disabled="disableForm"
            @change="getGitPath"
          >
            <el-option
              v-for="item in gitpathList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-row>
      <el-row
        v-if="form.fileObtainingType === 'git'"
        style="margin-top: 20px"
      >
        <el-form-item
          label="分支名"
          prop="gitBranchName"
        >
          <!-- <el-input
            v-model="form.gitBranchName"
            size="large"
            style="width: 300px"
            type="text"
          /> -->
          <el-select
            v-model="form.gitBranchName"
            filterable
            clearable
            size="large"
            placeholder="请选择git分支"
            :disabled="disableForm"
            style="width: 300px"
          >
            <el-option
              v-for="item in gitbranchList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-row>
      <el-row v-if="form.fileObtainingType === 'upload'">
        <el-upload
          ref="initScript"
          :disabled="disableForm"
          class="upload-demo"
          :action="action"
          :headers="headers"
          name="file"
          :on-remove="handleRemoveInitScript"
          :before-remove="beforeRemoveInitScript"
          :before-upload="beforeAvatarUpload"
          multiple
          drag
          :limit="1"
          :on-exceed="handleExceedInitScript"
          :on-success="handleSuccessInitScript"
          :on-error="handleErrorInitScript"
          :file-list="initScriptFileList"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将【发布包】拖到此处，或<em>点击上传</em></div>
          <div
            slot="tip"
            class="el-upload__tip"
          >只能上传.zip文件，且不超过100MB</div>
        </el-upload>
      </el-row>
    </el-col>
  </div>
</template>

<script>
import clusterSparingApi from '@/api/cluster/clusterSparing'
import {getToken} from '@/utils/auth'
import { getInfo } from '@/api/login'
import userApi from '@/api/system/user'
import roleGitApi from '@/api/script/config/roleGit'
import gitConfigApi from '@/api/script/config/gitConfig'
import scriptPackTaskApi from '@/api/script/pack/scriptPackTask'

export default {
  name: 'UploadScript',
  model: {
    prop: 'form',
    event: 'changes'
  },
  props: {
    disableForm: {
      type: Boolean,
      default: false
    },
    form: {
      type: Object
    },
    checkListTmp: {
      type: Array
    },
    initScriptListTmp: {
      type: Array
    },
    bizScriptListTmp: {
      type: Array
    },
    cycleScriptListTmp: {
      type: Array
    }
  },
  data() {
    return {
      action: '',
      headers: {
        'Authorization': getToken()
      },
      uploadFilePath: null,
      clusterList: [],
      checkListFileList: [],
      initScriptFileList: [],
      bizScriptFileList: [],
      cycleScriptFileList: [],
      schedulingConfigFileList: [],
      gitpathList: [],
      gitbranchList: []
    }
  },
  watch: {
    'form.gitBranchName': {
      handler: function(newVal, oldVal) {
        this.handleScriptNameMerge(newVal, oldVal)
      },
      deep: true
    },
    uploadFilePath(val) {
      const oldVal = `${this.fileName}`
      if (val.includes('/')) {
        const arr = val.split('/')
        this.fileName = arr[arr.length - 1].replace(new RegExp('.zip', 'g'), '')
      } else if (val.includes('\\')) {
        const arr = val.split('\\')
        this.fileName = arr[arr.length - 1].replace(new RegExp('.zip', 'g'), '')
      }

      this.handleScriptNameMerge(this.fileName, oldVal)
    }
  },
  created() {
    this.initCluster()
    this.getGit()
  },
  methods: {
    handleScriptNameMerge(prefix, oldPrefix) {
      if (!this.form.scriptPackName) { this.form.scriptPackName = '' }
      if (oldPrefix && this.form.scriptPackName.includes(oldPrefix)) {
        this.form.scriptPackName = this.form.scriptPackName.replace(oldPrefix, prefix)
      } else {
        this.form.scriptPackName = prefix + '_' + this.form.scriptPackName + '_' + Date.now()
      }
    },
    initCluster() {
      this.clusterList = []
      clusterSparingApi.findListByPage().then((res) => {
        console.log(res)
        const data = res.records
        data.forEach((array) => {
          this.clusterList.push({ value: array.id, label: array.clusterName })
        })
      })
    },
    // 获取git链接
    getGit() {
      var roleId = ''
      getInfo().then((res) => {
        userApi.get(res.id).then((data) => {
          roleId = data
          roleGitApi.findListById(roleId).then((res) => {
            res.forEach((array) => {
              gitConfigApi.findById(array.gitId).then((result) => {
                if (!(result.disabled == 'true')) {
                  this.gitpathList.push({value: result.gitpath, label: result.gitname})
                }
              })
            })
          })
        })
      })
    },

    // 获取git链接
    getGitPath(gitpath) {
      if (gitpath !== '') {
        var username = ''
        var password = ''
        gitConfigApi.findListNoPage({gitpath: gitpath}).then((res) => {
          username = res[0].username
          password = res[0].password
          scriptPackTaskApi.getBranch({gitpath: gitpath, username: username, password: password}).then((res) => {
            this.gitbranchList = res
            console.log(this.gitbranchList)
          })
        })
      }
    },

    beforeAvatarUpload(file) {
      return new Promise((resolve) => {
        this.$nextTick(() => {
          this.action = process.env.VUE_APP_BASE_API + '/api/scriptPack/task/upload'
          resolve()
        })
      })
    },
    // 上线清单文件上传操作 start
    handleRemoveCheckList(file, fileList) {
      this.form.checkList.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form.checkList.splice(index, 1)
        }
      })
      this.checkListTmp.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.checkListTmp.splice(index, 1)
        }
      })
    },
    handleExceedCheckList(files, fileList) {
      this.$message.warning(`上线清单只能上传一个`)
    },
    beforeRemoveCheckList(file, fileList) {
      return this.$confirm(`确定删除【${file.name}】吗？`)
    },
    handleSuccessCheckList(response, file, fileList) {
      this.form.checkList.push({ uid: file.uid, filePath: response })
    },
    handleErrorCheckList(err, file, fileList) {
      const message = JSON.parse(err.message)
      this.$message.error(`上线清单【${file.name}】:${message.message}`)
      this.$refs.checkList.uploadFiles.splice(this.$refs.checkList.uploadFiles.indexOf(file), 1)
    },
    // 上线清单文件上传操作 end
    // 初始脚本上传操作 start
    handleRemoveInitScript(file, fileList) {
      this.form.initScriptList.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form.initScriptList.splice(index, 1)
        }
      })
      this.initScriptListTmp.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.initScriptListTmp.splice(index, 1)
        }
      })
    },
    beforeRemoveInitScript(file, fileList) {
      return this.$confirm(`确定删除【${file.name}】吗？`)
    },
    handleExceedInitScript(files, fileList) {
      this.$message.warning(`仅支持上传单个扫描脚本包`)
    },
    handleSuccessInitScript(response, file, fileList) {
      this.form.initScriptList = []
      this.form.initScriptList.push({ uid: file.uid, filePath: response })
      const scriptPath = this.form.initScriptList[0].filePath
      console.log(scriptPath)
      this.uploadFilePath = scriptPath
    },
    handleErrorInitScript(err, file, fileList) {
      const message = JSON.parse(err.message)
      this.$message.error(`上线清单【${file.name}】:${message.message}`)
      this.$refs.initScript.uploadFiles.splice(this.$refs.initScript.uploadFiles.indexOf(file), 1)
    },
    // 初始脚本上传操作 end
    // 下载、推送、稽核脚本上传操作 start
    handleRemoveBizScript(file, fileList) {
      this.form.bizScriptList.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form.bizScriptList.splice(index, 1)
        }
      })
      this.bizScriptListTmp.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.bizScriptListTmp.splice(index, 1)
        }
      })
    },
    beforeRemoveBizScript(file, fileList) {
      return this.$confirm(`确定删除【${file.name}】吗？`)
    },
    handleExceedBizScript(files, fileList) {
      this.$message.warning(`超过5个下载、推送、稽核脚本需要压缩后再进行上传`)
    },
    handleSuccessBizScript(response, file, fileList) {
      this.form.bizScriptList.push({ uid: file.uid, filePath: response })
    },
    handleErrorBizScript(err, file, fileList) {
      const message = JSON.parse(err.message)
      this.$message.error(`上线清单【${file.name}】:${message.message}`)
      this.$refs.bizScript.uploadFiles.splice(this.$refs.bizScript.uploadFiles.indexOf(file), 1)
    },
    // 下载、推送、稽核脚本上传操作 end
    // 周期脚本上传操作 start
    handleRemoveCycleScript(file, fileList) {
      this.form.cycleScriptList.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form.cycleScriptList.splice(index, 1)
        }
      })
      this.cycleScriptListTmp.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.cycleScriptListTmp.splice(index, 1)
        }
      })
    },
    beforeRemoveCycleScript(file, fileList) {
      return this.$confirm(`确定删除【${file.name}】吗？`)
    },
    handleExceedCycleScript(files, fileList) {
      this.$message.warning(`调度配置只能上传一个`)
    },
    handleSuccessCycleScript(response, file, fileList) {
      this.form.cycleScriptList.push({ uid: file.uid, filePath: response })
    },
    handleErrorCycleScript(err, file, fileList) {
      const message = JSON.parse(err.message)
      this.$message.error(`上线清单【${file.name}】:${message.message}`)
      this.$refs.cycleScript.uploadFiles.splice(this.$refs.cycleScript.uploadFiles.indexOf(file), 1)
    },
    // 周期脚本上传操作 end
    // 调度配置上传操作 start
    handleRemoveSchedulingConfig(file, fileList) {
      this.form.schedulingConfig.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form.schedulingConfig.splice(index, 1)
        }
      })
    },
    beforeRemoveSchedulingConfig(file, fileList) {
      return this.$confirm(`确定删除【${file.name}】吗？`)
    },
    handleExceedSchedulingConfig(files, fileList) {
      this.$message.warning(`超过5个周期脚本需要压缩后再进行上传`)
    },
    handleSuccessSchedulingConfig(response, file, fileList) {
      this.form.schedulingConfig.push({ uid: file.uid, filePath: response })
    },
    handleErrorSchedulingConfig(err, file, fileList) {
      const message = JSON.parse(err.message)
      this.$message.error(`上线清单【${file.name}】:${message.message}`)
      this.$refs.schedulingConfig.uploadFiles.splice(this.$refs.schedulingConfig.uploadFiles.indexOf(file), 1)
    }
    // 调度配置上传操作 end
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/deep/.el-upload-dragger .el-upload__text {
  font-size: 0.7rem;
}

/deep/.el-upload-dragger {
  width: 260px;
}

.script-uploads-container {
  display: flex;
  overflow-x: scroll;
  gap: 1rem;
  padding: 0 0 1rem 0;
}

.upload-demo {
  text-align: center;
}
</style>
